package com.information.service;

import com.information.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.htmq.annotation.InforSuiteHTMQListener;
import org.springframework.stereotype.Service;

import java.util.Map;
import javax.annotation.PostConstruct;

@Service
public class UserEventConsumer {
    
    @Autowired
    private OperationLogService operationLogService;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    /**
     * 监听用户事件消息
     */
    @InforSuiteHTMQListener(topics = "user-event", groupId = "user-event-consumer-group")
    public void handleUserEvent(String message) {

        
        try {
            Map<String, Object> eventData = objectMapper.readValue(message, Map.class);

            String eventId = (String) eventData.get("eventId");
            String operationType = (String) eventData.get("operationType");
            String operatedBy = (String) eventData.get("operatedBy");
            Object userId = eventData.get("userId");
            
            // 修改：从 "user" 字段获取用户数据，而不是 "userDataSnapshot"
            Map<String, Object> userDataSnapshot = (Map<String, Object>) eventData.get("user");

            
            if (operationType != null && userDataSnapshot != null) {
                // 重构用户对象用于日志记录
                User user = reconstructUserFromSnapshot(userDataSnapshot);

                // 调用日志服务记录操作
                operationLogService.logOperation(operationType, user, operatedBy);
                
            } else {
                System.err.println("事件数据不完整: operationType=" + operationType + ", userDataSnapshot=" + userDataSnapshot);
            }
            
        } catch (Exception e) {
            System.err.println("处理用户事件消息失败: " + e.getMessage());
            e.printStackTrace();
        }
        
    }
    
    /**
     * 从快照数据重构User对象
     */
    private User reconstructUserFromSnapshot(Map<String, Object> snapshot) {
        User user = new User();
        
        try {
            if (snapshot.get("id") != null) {
                user.setId(((Number) snapshot.get("id")).longValue());
            }
            user.setUsername((String) snapshot.get("username"));
            user.setName((String) snapshot.get("name"));
            user.setEmail((String) snapshot.get("email"));
            user.setPhone((String) snapshot.get("phone"));
            
            if (snapshot.get("age") != null) {
                user.setAge(((Number) snapshot.get("age")).intValue());
            }
            
            user.setGender((String) snapshot.get("gender"));
            user.setAddress((String) snapshot.get("address"));
            
            // 处理枚举类型
            String roleStr = (String) snapshot.get("role");
            if (roleStr != null) {
                try {
                    user.setRole(User.UserRole.valueOf(roleStr));
                } catch (IllegalArgumentException e) {
                    user.setRole(User.UserRole.USER);
                }
            }
            
            String statusStr = (String) snapshot.get("status");
            if (statusStr != null) {
                try {
                    user.setStatus(User.UserStatus.valueOf(statusStr));
                } catch (IllegalArgumentException e) {
                    user.setStatus(User.UserStatus.ACTIVE);
                }
            }
            
            if (snapshot.get("isDelete") != null) {
                user.setIsDelete((Boolean) snapshot.get("isDelete"));
            }
            
        } catch (Exception e) {
            System.err.println("重构用户对象失败: " + e.getMessage());
        }
        
        return user;
    }
}